package org.springboot.mybatis.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

@Configuration
@MapperScan(basePackages = "org.springboot.mybatis.dao.two.mapper", 
			sqlSessionFactoryRef = "sqlSessionFactoryTwo")
public class MybatisTwoConfig {
	
	@Value("${mybatis.two.mapper-locations}")
    private String mapperLocations;

	@Value("${mybatis.two.type-aliases-package}")
    private String typeAliasesPackage;

	@Value("${mybatis.two.configuration.map-underscore-to-camel-case}")
    private boolean mapUnderscoreToCamelCase;

	@Autowired
	@Qualifier("dataSourceTwo")
    DataSource dataSourceTwo;

    @Bean
    @Primary
    public SqlSessionFactoryBean sqlSessionFactoryTwo() throws Exception {
    	SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSourceTwo);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(mapperLocations));
        sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);
        // 开启驼峰转换
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBean.getObject();
        org.apache.ibatis.session.Configuration configuration =  sqlSessionFactory.getConfiguration();
        configuration.setMapUnderscoreToCamelCase(mapUnderscoreToCamelCase);
        return sqlSessionFactoryBean;
    }
}
